/**
 * Copyright (C) 2009 Noel Ang
 *
 * This file is part of Samsara.
 *
 * Samsara is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Samsara is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Samsara.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package com.lunarshades.samsara;

import com.lunarshades.samsara.ui.Utils;

/**
 * Represents a scalar value of entitlement.
 *
 * @author Noel Ang, sparta.variable@gmail.com
 */
public class Karma implements Comparable {

public Karma(final int initialValue) {
    mValue = initialValue;
}

public static Karma valueOf(Object value) {
    try {
        return new Karma(Utils.makeInt(value));
    } catch (Exception e) {
        return null;
    }
}

public int compareTo(Object o) {
    Karma that = (Karma) o;
    return this.mValue - that.mValue;
}

public synchronized void create(final int amount) {
    if (amount < 0) {
        mValue = Math.max(0, mValue + amount);
    } else {
        if (mValue - amount <= Integer.MAX_VALUE - amount) {
            mValue += amount;
        } else {
            mValue = Integer.MAX_VALUE;
        }
    }
}

public int intValue() {
    return mValue;
}

@Override
public synchronized int hashCode() {
    return String.valueOf(mValue).intern().hashCode();
}

@Override
public boolean equals(Object obj) {
    if (obj != null) {
        if (obj instanceof Karma) {
            synchronized (this) {
                return obj == this || (((Karma) obj).mValue == this.mValue);
            }
        }
    }
    return false;
}

@Override
public synchronized String toString() {
    return String.valueOf(mValue).intern();
}

private volatile int mValue = 0;

}
